﻿using UnityEngine;
using System.Collections;
using System.Xml;
using NumberKnightConstants;
using System.Linq;
using System.Collections.Generic;

public class Networking : MonoBehaviour {

    XmlDocument xml;
	string url = "https://api.scoreoid.com/v1/{0}";
	string uiText = "";
	PlayerContainer p = new PlayerContainer();
	ScoreContainer scoreContainer = new ScoreContainer();
	SuccessContainer success = new SuccessContainer();
	Vector2 scrollPosition = Vector2.zero; 
	public GUISkin customSkin;
	protected GUIStyle backgroundStyle;
	protected GUIStyle UIBox;
	protected GUIStyle UIButton;
 	public void Start () {
		GetStyles ();   
    }
	void GetStyles()
	{
		backgroundStyle = customSkin.customStyles [0];
		UIBox = customSkin.customStyles [1];
		UIButton = customSkin.customStyles [2];
	}
	public void getScores(int startIndex = 0, int endIndex = 10)
	{
		string scoresUrl = string.Format (url, "getScores");
		WWWForm scoresForm = setUpForm ();
		scoresForm.AddField ("limit", startIndex + "," + endIndex);
		scoresForm.AddField ("order_by", "score");
		PostForm (scoresForm, scoresUrl, scoreContainer);
	}
	public void getPlayers()
	{
		string playersUrl = string.Format (url, "getPlayers");
		WWWForm playersForm = setUpForm ();
		PostForm (playersForm, playersUrl, p);

	}
	public void postScore(int score)
	{
		string postScoreUrl = string.Format (url, "createScore");
		WWWForm postScoreForm = setUpForm ();
		postScoreForm.AddField ("username", PlayerPrefs.GetString ("username"));
		postScoreForm.AddField ("score", score);
		PostForm (postScoreForm, postScoreUrl, success);
	}
	WWWForm setUpForm()
	{
		WWWForm form = new WWWForm();
		
		form.AddField("api_key", Constants.api_key);
		form.AddField("game_id", Constants.game_id);
		form.AddField("response", Constants.responseType);

		return form;
	}
	void PostForm(WWWForm form, string url, object returnType)
	{
		WWW www = new WWW(url, form);
		StartCoroutine(WaitForRequest(www, returnType));
	}

	protected void OnGUI()
	{
		UIBox.fontSize = Mathf.Clamp ((int)((Screen.height * Screen.width) * 0.00003f), 20, 40);
		UIBox.contentOffset = new Vector2 (0, Screen.height * 0.025f);
	}
	public void LeaderBoard(Rect area, int amountOfScores) 
	{
		if (Input.touchCount > 0) {
						var touch = Input.touches [0];
						if (touch.phase == TouchPhase.Moved && area.Contains (touch.position))
								scrollPosition.y += touch.deltaPosition.y;
				}

		float boxHeight = 50f; 		
		if (scoreContainer.Players != null) {
						float areaHeight = boxHeight * scoreContainer.Players.Count (); 	
						scrollPosition = GUI.BeginScrollView (area, scrollPosition, new Rect (area.x, area.y, 15, areaHeight), customSkin.horizontalScrollbar, customSkin.verticalScrollbar);

						for (int i = 0; i < amountOfScores && i < scoreContainer.Players.Count(); i++) { 	
								GUI.Box (new Rect (0, area.y + (boxHeight) * i, area.width, boxHeight), i + 1 + ". " + scoreContainer.Players [i].Username + " : " + scoreContainer.Players [i].score [0].Score,UIButton); 
						}
			
						GUI.EndScrollView ();
				}
		else
			GUI.Box (area, "Loading", customSkin.box);	
	}

    IEnumerator WaitForRequest(WWW www, object container)
    {
        yield return www;

		if (container is PlayerContainer)
						DeserializePlayer (www.text);
		if (container is ScoreContainer)
						DeserializeScore (www.text);
		if (container is SuccessContainer)
						DeserializeSuccess (www.text);
        /* Check for errors */
        if (www.error == null) {
						Debug.Log (www.text);
		}
         else {
            Debug.Log("WWW Error: "+ www.error);
		}
	}
	public void DeserializePlayer(string xmlToParse)
	{
		p = PlayerContainer.LoadFromText(xmlToParse);
	}
	public void DeserializeScore(string xmlToParse)
	{
		scoreContainer = ScoreContainer.LoadFromText(xmlToParse);
	}
	public void DeserializeSuccess(string xmlToParse)
	{
		success = SuccessContainer.LoadFromText (xmlToParse);
		Debug.Log (success.Message);
		
	}
}
